﻿using System;
using System.Linq;
using AutoStopApp.Core;
using AutoStopData.BussinessLogic;
using AutoStopData.Domains;
using AutoStopData.Model;

namespace AutoStopApp.Controls
{
    public partial class UserLogIn : AjaxUserControl
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            btnLogIn.Click += BtnLogInClick;
            Load += PageLoad;
        }

        protected void PageLoad(object sender, EventArgs e)
        {
            var page = (AjaxPage)Page;
            InitializeAjaxControls(page.AjaxManager, page.LoadingPanel);
            AddAjaxSetting(btnLogIn, pnlLogIn);
        }

        void BtnLogInClick(object sender, EventArgs e)
        {
            var user = Users.GetByMail(txtMail.Text);
            if (user != null && user.Password == txtPassword.Text)
            {
                var url = WsaaManager.Data.First(ai => ai.Resource == WsaaManager.WsaaResource.DefaultInnerPage && ai.UserTypeName == GetUserTypeName(SessionProvider.CurrentSession)).MenuItem.Url;
                if (user.Banned)
                {
                    url += "?message=BANNED";
                }
                else
                {
                    if (SessionProvider.CurrentSession != null)
                    {
                        throw new Exception("Already logged.");
                    }
                    var session = new Session();
                    session.UserId = user.UserId;
                    session.LoggedIn = DateTime.Now;
                    session.LastAccess = session.LoggedIn;
                    session.HasLoggedOut = false;
                    Sessions.Insert(session);

                    session.User = user;
                    SessionProvider.CurrentSession = session;
                }
                Response.Redirect(url);
            }
            else
            {
                litMessage.Text = "Nesprávne meno alebo heslo";
            }
        }

        private static UserTypes.Name GetUserTypeName(Session session)
        {
            var retVal = UserTypes.Name.None;
            if (session != null)
            {
                retVal = UserTypes.GetName(session.User.UserTypeCode);
            }
            return retVal;
        }
    }
}